package cn.itcast.n4_共享模型_管程;

import cn.itcast.util.Downloader;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.List;

/**
 * @program: juc
 * @description:
 * @author: flyduck
 * @create: 2024-10-08 16:54
 **/
@Slf4j(topic = "c.Test29_$$$$$_wait_notify设计模式_一个线程等待另外一个线程执行结果_保护性暂停")
public class Test29_$$$$$_wait_notify设计模式_一个线程等待另外一个线程执行结果_保护性暂停 {
    public static void main(String[] args) {
        //线程1 等待 线程2 的下载结果
        GuardedObject1 guardedObject1 = new GuardedObject1();

        new Thread(() -> {
            //等待结果
            log.debug("等待结果中......");
            List<String> result = (List<String>) guardedObject1.getResult();
            log.debug("结果大小:{}",result.size());
        },"t1").start();

        new Thread(() -> {
            log.debug("执行下载中......");
            try {
                List<String> list = Downloader.download();
                guardedObject1.setResult(list);
            } catch (IOException e) {
                e.printStackTrace();
            }
        },"t2").start();
    }
}

class GuardedObject1{
    private Object result;//等待的结果

    public Object getResult() {
        synchronized (this) {
            while (result == null) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return result;
        }
    }

    public void setResult(Object result) {
        synchronized (this) {
            this.result = result;
            this.notifyAll();
        }
    }
}
